(function(){

    var progressSupport = ('onprogress' in new Browser.Request());

    Request.File = new Class({

        Extends: Request,

        options: {
            emulation: false,
            urlEncoded: false
        },

        initialize: function(options){
            this.xhr = new Browser.Request();
            this.formData = new FormData();
            this.setOptions(options);
            this.headers = this.options.headers;
        },

        append: function(key, value){
            this.formData.append(key, value);
            return this.formData;
        },

        reset: function(){
            this.formData = new FormData();
        },

        send: function(options){
            if (!this.check(options)) return this;

            this.options.isSuccess = this.options.isSuccess || this.isSuccess;
            this.running = true;

            var xhr = this.xhr;
            if (progressSupport){
                xhr.onloadstart = this.loadstart.bind(this);
                xhr.onprogress = this.progress.bind(this);
                xhr.upload.onprogress = this.progress.bind(this);
            }

            xhr.open('POST', this.options.url, true);
            xhr.onreadystatechange = this.onStateChange.bind(this);

            Object.each(this.headers, function(value, key){
                try {
                    xhr.setRequestHeader(key, value);
                } catch (e){
                    this.fireEvent('exception', [key, value]);
                }
            }, this);

            this.fireEvent('request');
            xhr.send(this.formData);

            if (!this.options.async) this.onStateChange();
            if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
            return this;
        }

    });

})();

function getUserInfo(username, pass){
    return {
        "username": username,
        "password": pass
    }
}

function getLoginMessage(username, pass){
    var retorno = "";
    retorno += "110";
    retorno += JSON.encode(getUserInfo(username, pass));
    return retorno;
}

function getRegisterMessage(username, pass){
    var retorno = "";
    retorno += "120";
    retorno += JSON.encode(getUserInfo(username, pass));
    return retorno;
}


function getPostInfo(id, text, hasPic, isNow, picLoc, date, channel, comment, postId){
    return {
        "id" : id,
        "text" : text,
        "hasPic" : hasPic,
        "isNow" : isNow,
        "picLoc" : picLoc,
        "date" : date,
        "channel" : channel,
        "comment" : comment,
        "postId" : postId
    }
}

function getNewMessagePostInfo(text, hasPic, isNow, picLoc, date){
    return getPostInfo(-1,text, hasPic, isNow, picLoc, date,-1,false,-1);
}

function getNewCommentPostInfo(text, postId){
    return getPostInfo(-1,text, false, true, "", "",-1,true,postId);
}

function getEditMessagePostInfo(text, postId){
    return getPostInfo(postId,text, false, true, "", "",-1,false,postId);
}

function getEliminatePostInfo(id, isComment){
    return getPostInfo(id,"", false, true, "", "",-1,isComment,id);
}


function getNewPostMessage(text, hasPic, isNow, picLoc, date){
    var retorno = "";
    retorno += "210";
    retorno += JSON.encode(getNewMessagePostInfo(text, hasPic, isNow, picLoc, date));
    return retorno;
}

function getNewCommentMessage(text, postId){
    var retorno = "";
    retorno += "210";
    retorno += JSON.encode(getNewCommentPostInfo(text, postId));
    return retorno;
}

function getEditPostMessage(text, postId){
    var retorno = "";
    retorno += "220";
    retorno += JSON.encode(getEditMessagePostInfo(text, postId));
    return retorno;
}

function getEliminatePostMessage(postId){
    var retorno = "";
    retorno += "230";
    retorno += JSON.encode(getEliminatePostInfo(postId, false));
    return retorno;
}

function getEliminateCommentMessage(postId){
    var retorno = "";
    retorno += "230";
    retorno += JSON.encode(getEliminatePostInfo(postId, true));
    return retorno;
}


function getPMInfo(from, texto, to){
    return {
        "from":from,
        "text":texto,
        "to":to
    }
}

function getNewPMInfo(from, texto, to){
    return getPMInfo(from, texto, to);
}

function getNewPmMessage(texto, to){
    var retorno = "";
    retorno += "310";
    retorno += JSON.encode(getNewPMInfo(loggedUser.username, texto, to));
    return retorno;
}


function getChannelInfo(name, data){
    return {
        "name":name,
        "data":data
    }
}

function getCriarChannelMessage(name){
    var retorno = "";
    retorno += "420";
    retorno += JSON.encode(getChannelInfo(name, ""));
    return retorno;
}

function getSairChannelMessage(name){
    var retorno = "";
    retorno += "430";
    retorno += JSON.encode(getChannelInfo(name, ""));
    return retorno;
}

function getMsgChannelMessage(name, msg){
    var retorno = "";
    retorno += "440";
    retorno += JSON.encode(getChannelInfo(name, ""+msg));
    return retorno;
}













function getFormatedDate(){
    var datas = new Date().toISOString();
    datas = datas.substring(0,10);
    var datap = datas.split('-');
    return datap[2]+"-"+datap[1]+"-"+datap[0];
}

function getFormatedTime(){
    return new Date().toLocaleTimeString();
}









var websocket;
var knownUsers = [];

var st = new LocalStorage();
st.set('name',{
    a:'aaa',
    b:'bbb'
});
//on another day/page
st.get('name');

function saveusers(){
    st.set('userlist', knownUsers);
}

function loadusers(){
    if(st.get('userlist').length>0){
        knownUsers = st.get('userlist');
    }else {
        knownUsers = [];
    }
}

function adduser(user){
    if(!userExists(user.username)){
        knownUsers.push(user);
    }
    saveusers();
}

function addusers(users){
    for(var u=0; u<users.length; u++){
        if(!userExists(users[u].username)){
            knownUsers.push(users[u]);
        }
    }
    saveusers();
}

function userExists(username){
    for(var u=0; u<knownUsers.length; u++){
        if(knownUsers[u].username==username){
            return true;
        }
    }
    return false;
}

window.onload = function() { // execute once the page loads
    initialize();
    initializeChatGUI();
    loadusers();
}

function initialize() { // URI = ws://10.16.0.165:8080/chat/chat
    connect('ws://' + window.location.host + '/chatsd/HTTPBridge');
}

function connect(host) { // connect to the host websocket servlet
    if ('WebSocket' in window)
        websocket = new WebSocket(host);
    else if ('MozWebSocket' in window)
        websocket = new MozWebSocket(host);
    else {
        writeToHistory('Get a real browser which supports WebSocket.');
        return;
    }

    websocket.onopen    = onOpen; // set the event listeners below
    websocket.onclose   = onClose;
    websocket.onmessage = onMessage;
    websocket.onerror   = onError;
}

function onOpen(event) {
    writeToHistory('Connected to ' + window.location.host + '.');
}
        
function onClose(event) {
    writeToHistory('WebSocket closed.');
}
        
function onMessage(message) { // print the received message
    parseMessageWeb(message.data);
}
        
function onError(event) {
    writeToHistory('WebSocket error (' + event.data + ').');
}
        
function doSend(message) {
    websocket.send(message); // send the message
}

function writeToHistory(text) {
    var history = document.getElementById('history');
    var p = document.createElement('p');
    p.style.wordWrap = 'break-word';
    p.innerHTML = text;
    history.appendChild(p);
    while (history.childNodes.length > 25)
        history.removeChild(console.firstChild);
    history.scrollTop = history.scrollHeight;
}


var loginPanel,listaSalasPanel,salaItemPanel,salaPanel,mpPanel,simplePostPanel,imagePostPanel,commentPanel,newPostPanel,editPostPanel,newCommentPanel,userItemPanel,mpItemPanel,newMPPanel;

var knownDB = {
    "posts":[],
    "comments":[],
    "users":[],
    "pms":[]
};

var control = {
    "hasMainRoom":false,
    "selectedPM":-1
};

var loggedUser = {
    'username':"",
    'id':-1
};

var mainPanelsIds = [];

var chatChannelsInfo = [];

function chatChannelExists(name){
    if(getChatChannelId(name)>=0){
        return true;
    }
    return false;
}

function getChatChannelId(name){
    for(var c=0; c<chatChannelsInfo.length; c++){
        if(chatChannelsInfo[c].name==name){
            return c;
        }
    }
    return -1;
}


function createChannelsListPanel(){
    var listPanel = new Element('div', {
        "id":"channelsList",
        styles:{
            "width": "100%",
            "height":"100%",
            "display":"none"
        }
    }).adopt(new Element('div', {
        "id":"channels",
        styles:{
            "width": "100%"
        }
    })).adopt(new Element('div', {
        "id":"newchannel",
        styles:{
            "width": "100%"
        }
    }).adopt(new Element('input',{
        "type":"text",
        "id":"newchannelname",
        "name":"newchannelname",
        "value":""
    })).adopt(new Element('input',{
        "type":"button",
        "id":"newchannelbut",
        "name":"newchannelbut",
        "value":"Criar Canal",
        events : {
            click: function(){
                criarChannel($('newchannelname').get('value'));
            }
        }
    })));
    $('mainContent').adopt(listPanel);
    mainPanelsIds.push("channelsList");
    $('mainButtons').adopt(mainButton('clBut', 'Canais', function(){
        clickedMBut('channelsList');
    }));
}

function updateChannelList(){
    $('channels').setStyle('width','890px');
    $('channels').setStyle('height','400px');
    $('channels').empty();
    for(var c=0; c<chatChannelsInfo.length; c++){
        var channelPan = new Element('div', {
            "id":"channel"+c,
            "channelname": chatChannelsInfo[c].name,
            styles:{
                "padding": "2px",
                "margin": "2px",
                "width": "170px",
                "height": "30px",
                "border": "1px solid #000000",
                "float": "left",
                "cursor": "pointer"
            },
            events : {
                click : function(){
                    enterChannel(this.get('channelname'));
                }
            }
        }).set('text', chatChannelsInfo[c].name);
        $('channels').adopt(channelPan);
    }
    
}

function updateUserList(chatInfo){
    $(chatInfo.name+'users').empty();
    for(var h=0; h<chatInfo.users.length; h++){
        var tempUserPanel = userItemPanel.clone();
        tempUserPanel.set('id', chatInfo.name+'user'+chatInfo.users[h]);
        tempUserPanel.set('text', chatInfo.users[h]);
        $(chatInfo.name+'users').adopt(tempUserPanel);
    }
}

function enterChannel(name){
    doSend(getCriarChannelMessage(name));
    if($("room_"+name)==null){
        var cId = getChatChannelId(name);
    
        var chatPanel = salaPanel.clone();
        chatPanel.set('id', "room_"+name);    
        chatPanel.setStyle('display','none');
        chatPanel.getChildren()[0].getChildren()[0].set('id',name+'msgs');
        chatPanel.getChildren()[0].getChildren()[1].set('id',name+'users');
        chatPanel.getChildren()[1].adopt(new Element('input',{
            "type":"text",
            "id":name+"input",
            "name":name+"input",
            "value":""
        }));
        chatPanel.getChildren()[1].getChildren()[0].onkeydown = function(key) {
            if (key.keyCode == 13){
                //send msg
                doSend(getMsgChannelMessage(name, this.get('value')));
                this.set('value', '');
            }
        };
        chatPanel.getChildren()[1].adopt(new Element('input',{
            "type":"button",
            "id":name+"escreve",
            "name":name+"escreve",
            "value":"Envia",
            "channelname":name,
            events : {
                click: function(){
                    doSend(getMsgChannelMessage(name, $(this.get('channelname')+'input').get('value')));
                    $(this.get('channelname')+'input').set('value', '');
                }
            }
        }));
        chatPanel.getChildren()[1].adopt(new Element('input',{
            "type":"button",
            "id":name+"leave",
            "name":name+"leave",
            "value":"Sair do Canal",
            "channelname":name,
            events : {
                click: function(){
                    sairChannel(this.get('channelname'));
                }
            }
        }));
        $('mainContent').adopt(chatPanel);
    
        if(cId>=0){
            updateUserList(chatChannelsInfo[cId]);
        }
    
        mainPanelsIds.push("room_"+name);
        $('mainButtons').adopt(mainButton(name+'But', name, function(){
            clickedMBut("room_"+name);
        }));
    }
    
    clickedMBut("room_"+name);
}

function sairChannel(name){
    clickedMBut('channelsList');
    $('mainButtons').removeChild($(name+'But'));
    mainPanelsIds.erase("room_"+name);
    $("room_"+name).dispose();
    //send message sair canal
    doSend(getSairChannelMessage(name));
}

function criarChannel(name){
    //send message criar canal
    enterChannel(name);
    
}

function updateChannelsDB(data){
    chatChannelsInfo = data;
    for(var h=0; h<chatChannelsInfo.length; h++){
        if($('room_'+chatChannelsInfo[h].name)!=null){
            updateUserList(chatChannelsInfo[h]);
        }
    }
    updateChannelList();
}


            
function removeAndSavePanels(){
    loginPanel = $('divLogin').clone();
    $('divLogin').dispose();
                
    salaItemPanel = $('panelSala').clone();
    $('panelSala').dispose();
    listaSalasPanel = $('divSalas').clone();
    $('divSalas').dispose();
                
    simplePostPanel = $('postsimples').clone();
    $('postsimples').dispose();                
    commentPanel = $('resposta').clone();
    $('resposta').dispose();                
    imagePostPanel = $('postimagem').clone();
    $('postimagem').dispose();
                
    newPostPanel = $('divNewPost').clone();
    $('divNewPost').dispose();
    newCommentPanel = $('divNewResposta').clone();
    $('divNewResposta').dispose();
    editPostPanel = $('divEditarPost').clone();
    $('divEditarPost').dispose();
                
    userItemPanel = $('panelusername').clone();
    $('panelusername').dispose();
                
    salaPanel = $('divCanal').clone();
    $('divCanal').dispose();
                
    mpItemPanel = $('panelMP').clone();
    $('panelMP').dispose();                
    newMPPanel = $('panelNewMP').clone();
    $('panelNewMP').dispose();
                
    mpPanel = $('divMensagensPrivadas').clone();
    $('divMensagensPrivadas').dispose();
}

function initializeChatGUI(){
    removeAndSavePanels();
    $('mainContent').empty();
    $('mainButtons').empty();
}
            
function mainButton(id, texto, onclick){
    var elem = new Element('div',{
        id: id,
        'class':'mainbutton',
        events : {
            'mouseenter' : function(){
                this.set('class', 'mainbuttonover');
            },
            'mouseleave' : function(){
                this.set('class', 'mainbutton');
            },
            'click' : onclick
        }
    }).set('text', texto);
    return elem;
}
            
function setLoginPanel(){
    $('mainContent').empty();
    $('mainContent').adopt(loginPanel.clone());    
    $('mainContent').firstChild.set('id', "divLogin");
    $('mainContent').getChildren()[0].getChildren()[0].setStyle('width', '500px');
    var rows = $('mainContent').getChildren()[0].getChildren()[0].getChildren()[0].getChildren();
    rows[0].getChildren()[1].getChildren()[0].set('id', 'username');
    rows[1].getChildren()[1].getChildren()[0].set('id', 'password');
    rows[2].getChildren()[1].getChildren()[0].set('id', 'confpassword');
    rows[2].getChildren()[0].set('id', 'confcell1');
    rows[2].getChildren()[1].set('id', 'confcell2');
    rows[3].getChildren()[1].getChildren()[0].set('id', 'isReg');
    rows[4].getChildren()[1].getChildren()[0].set('id', 'loginBut');
    rows[5].getChildren()[0].set('id', 'loginResponse');
    
    $('confcell1').setStyle('display', 'none');
    $('confcell2').setStyle('display', 'none');
    $('isReg').addEvents({
        click: function(){
            if($('isReg').checked){
                $('confcell1').setStyle('display', 'table-cell');
                $('confcell2').setStyle('display', 'table-cell');
            }else{
                $('confcell1').setStyle('display', 'none');
                $('confcell2').setStyle('display', 'none');
            }
        }
    });
    
    rows[4].getChildren()[1].getChildren()[0].addEvents({
        click: function(){
            if($('isReg').checked){
                if($('password').get('value')==$('confpassword').get('value')){
                    doSend(getRegisterMessage($('username').get('value'), $('password').get('value')));
                }else {
                    $('loginResponse').set('text','As passwords devem coincidir.');
                }
            }else{
                //alert(getLoginMessage($('username').get('value'), $('password').get('value')));
                doSend(getLoginMessage($('username').get('value'), $('password').get('value')));
            }
        }
    });
}


function initializeApplicationPanels(){
    $('mainContent').empty();
    var mainChatPanel = salaPanel.clone();
    mainChatPanel.set('id', "mainChatRoom");
    chats[0] = "mainChatRoom";
    
    var pmPanel = mpPanel.clone();
    pmPanel.set('id', "pmPanelDiv");
    
    
    $('mainContent').adopt(mainChatPanel);
    $('mainContent').adopt(pmPanel);
    pmPanel.setStyle('display', 'none');


    setNewPostPanel(0);
    control.hasMainRoom = true;
    
    $('pmPanelDiv').getChildren()[0].set('id', 'listaMP');
    $('pmPanelDiv').getChildren()[1].addEvents({
        click : function(){
            setNewMPPanel("", "");
        }
    });
    $('pmPanelDiv').getChildren()[2].addEvents({
        click : function(){
            if(control.selectedPM>=0){
                setNewMPPanel(knownDB.pms[control.selectedPM].from, knownDB.pms[control.selectedPM].text)
            }
        }
    });


    mainPanelsIds.push("mainChatRoom");
    mainPanelsIds.push("pmPanelDiv");
}

function clickedMBut(panId){
    //alert(panId);
    for(var t=0; t<mainPanelsIds.length; t++){
        if(panId==mainPanelsIds[t]){
            $(mainPanelsIds[t]).setStyle('display', 'block');
        }else {
            $(mainPanelsIds[t]).setStyle('display', 'none');
        }
    }
}

/*function initializeMainChatRoom(){
    $('mainContent').empty();
    $('mainContent').adopt(salaPanel.clone());    
    $('mainContent').firstChild.set('id', "mainChatRoom");
    chats[0] = "mainChatRoom";
    setNewPostPanel(0);
    control.hasMainRoom = true;
}

function initializePMPanel(){
    $('mainContent').adopt(mpPanel.clone());    
    $('mainContent').firstChild.set('id', "mainChatRoom");
    chats[0] = "mainChatRoom";
    setNewPostPanel(0);
    control.hasMainRoom = true;
}*/

function reloadSrc(elem){ 
    //var temp = elem.src;
    //elem.src = "";
    elem.src = elem.src;
    elem.onError = '(function(){reloadSrc($(\''+elem.id+'\'))}).delay(2000);';
//alert(temp);
}

function updateChatRoomPosts(chatroomid){
    var chatElement = $(chats[chatroomid]);
    chatElement.getChildren()[0].getChildren()[0].empty();
    if(chatroomid==0){
        for(var i=0; i<knownDB.posts.length; i++){
            var tempPost;
            if(knownDB.posts[i].hasPic){
                tempPost = imagePostPanel.clone();
            }else {
                tempPost = simplePostPanel.clone();
            }
            tempPost.set('id', 'post'+knownDB.posts[i].id);
            chatElement.getChildren()[0].getChildren()[0].adopt(tempPost);
            $('post'+knownDB.posts[i].id).getChildren()[0].getChildren()[0].set('text', 'Utilizador: '+knownDB.posts[i].utilizador);
            
            var isMyPost = (knownDB.posts[i].utilizador==loggedUser.username);
            var htmlButoes = "";
            
            if(isMyPost){
                htmlButoes += '<input id="'+'post'+knownDB.posts[i].id+'But1" class="inputButs" type="button" value="editar" style="margin: 4px" /><br />';
            }
            
            htmlButoes += '<input id="'+'post'+knownDB.posts[i].id+'But2" class="inputButs" style="margin: 4px" type="button" value="comentar" /><br />';
            
            if(isMyPost){
                htmlButoes += '<input id="'+'post'+knownDB.posts[i].id+'But3" class="inputButs" style="margin: 4px" type="button" value="eliminar" />';
            }
            
            $('post'+knownDB.posts[i].id).getChildren()[0].getChildren()[1].set('html', htmlButoes);
            
            if(knownDB.posts[i].hasPic){
                $('post'+knownDB.posts[i].id).getChildren()[1].empty();
                //alert(knownDB.posts[i].picLoc);
                var img = new Element('img', {
                    'id':'post'+knownDB.posts[i].id+'img',
                    'alt':'loading...',
                    'src':''+knownDB.posts[i].picLoc,
                    styles : {
                        'margin': '5px',
                        'display': 'inline',
                        'width': '170px',
                        'float': 'left'
                    },
                    events : {
                        error : function(){
                            (function(){
                                this.src = this.src;
                            }.bind(this)).delay(2000);
                            
                        }
                    }
                    
                });
                $('post'+knownDB.posts[i].id).getChildren()[1].set('text', ''+knownDB.posts[i].text);
                $('post'+knownDB.posts[i].id).getChildren()[1].adopt(img);
            //$('post'+knownDB.posts[i].id).getChildren()[1].set('idx', i);
                
            /*(function(){ 
                    var temp = this.src;
                    this.src = "";
                    this.src = temp;
                    //alert(temp);
                }.bind($('post'+knownDB.posts[i].id+'img'))).delay(5000);*/
            }else {
                $('post'+knownDB.posts[i].id).getChildren()[1].empty();
                $('post'+knownDB.posts[i].id).getChildren()[1].set('text', knownDB.posts[i].text);
            }
            
            $('post'+knownDB.posts[i].id+'But2').set('chatroom', chatroomid);
            $('post'+knownDB.posts[i].id+'But2').set('postid', i);
            $('post'+knownDB.posts[i].id+'But2').addEvents({
                click:function(){
                    setCommentPostPanel(this.get('chatroom'),this.get('postid'));
                //alert("edit post id "+knownDB.posts[i].id);
                }
            });
            
            if(isMyPost){
                $('post'+knownDB.posts[i].id+'But1').set('chatroom', chatroomid);
                $('post'+knownDB.posts[i].id+'But1').set('postid', i);
                $('post'+knownDB.posts[i].id+'But1').addEvents({
                    click:function(){
                        setEditPostPanel(this.get('chatroom'),this.get('postid'));
                    //alert("edit post id "+knownDB.posts[i].id);
                    }
                });
                $('post'+knownDB.posts[i].id+'But3').set('chatroom', chatroomid);
                $('post'+knownDB.posts[i].id+'But3').set('postid', i);
                $('post'+knownDB.posts[i].id+'But3').addEvents({
                    click:function(){
                        doSend(getEliminatePostMessage(knownDB.posts[this.get('postid')].id));
                    //alert("delete post id "+knownDB.posts[i].id);
                    }
                });
            }
            
            //Coments
            for(var c=0; c<knownDB.comments.length; c++){
                if(knownDB.posts[i].id==knownDB.comments[c].postId){
                    var isMyCom = (knownDB.comments[c].utilizador==loggedUser.username);
                    var tempCom = commentPanel.clone();
                    tempCom.set('id', 'com'+knownDB.comments[c].id);
                    
                    
                    chatElement.getChildren()[0].getChildren()[0].adopt(tempCom);
                    $('com'+knownDB.comments[c].id).getChildren()[0].getChildren()[0].set('text', 'Utilizador: '+knownDB.comments[c].utilizador);
            
                    var htmlCButoes = "";
            
            
                    if(isMyCom){
                        htmlCButoes += '<input id="'+'com'+knownDB.comments[c].id+'But1" class="inputButs" style="margin: 4px" type="button" value="eliminar" />';
                    }
            
                    $('com'+knownDB.comments[c].id).getChildren()[0].getChildren()[1].set('html', htmlCButoes);
            
                    
                    $('com'+knownDB.comments[c].id).getChildren()[1].empty();
                    $('com'+knownDB.comments[c].id).getChildren()[1].set('text', knownDB.comments[c].text);
                    
                    if(isMyPost){
                        $('com'+knownDB.comments[c].id+'But1').set('chatroom', chatroomid);
                        $('com'+knownDB.comments[c].id+'But1').set('postid', c);
                        $('com'+knownDB.comments[c].id+'But1').addEvents({
                            click:function(){
                                doSend(getEliminateCommentMessage(knownDB.comments[this.get('postid')].id));
                            //alert("edit post id "+knownDB.posts[i].id);
                            }
                        });
                    }
                }
            }          
        }
    
    }else {
        
}
}

function updateChatRoomUsers(chatroomid){
    var chatElement = $(chats[chatroomid]);
    chatElement.getChildren()[0].getChildren()[0].empty();
    chatElement.getChildren()[0].getChildren()[1].set('id',chatroomid+'userlist');
    chatElement.getChildren()[0].getChildren()[1].empty();
    for(var h=0; h<knownDB.users.length; h++){
        var tempUserPanel = userItemPanel.clone();
        tempUserPanel.set('id', chatroomid+'user'+knownDB.users[h].password);
        tempUserPanel.set('text', knownDB.users[h].username);
        chatElement.getChildren()[0].getChildren()[1].adopt(tempUserPanel);
    }
}

function setNewPostPanel(chatroomid){
    var chatElement = $(chats[chatroomid]);
    chatElement.getChildren()[1].empty();
    
    var tempNPPanel = newPostPanel.clone();
    chatElement.getChildren()[1].adopt(tempNPPanel);
    tempNPPanel.set('id', 'newPostDiv'+chatroomid);
    
    tempNPPanel.getChildren()[1].set('id', 'checkBoxAgora'+chatroomid);
    tempNPPanel.getChildren()[2].set('id', 'data1'+chatroomid);
    tempNPPanel.getChildren()[2].set('value', getFormatedDate());
    tempNPPanel.getChildren()[3].set('id', 'data2'+chatroomid);
    tempNPPanel.getChildren()[3].set('value', getFormatedTime());
    tempNPPanel.getChildren()[5].set('id', 'formpicupload'+chatroomid);
    tempNPPanel.getChildren()[5].getChildren()[0].set('id', 'checkBoxPic'+chatroomid);
    tempNPPanel.getChildren()[5].getChildren()[1].set('id', 'inputPic'+chatroomid);
    tempNPPanel.getChildren()[5].getChildren()[2].set('id', 'butSubmit'+chatroomid);
    tempNPPanel.getChildren()[8].set('id', 'texto'+chatroomid);
    tempNPPanel.getChildren()[9].set('id', 'butEnviar'+chatroomid);
    tempNPPanel.getChildren()[10].set('id', 'butCancelar'+chatroomid);
    
    tempNPPanel.getChildren()[10].addEvents({
        click:function(){
            setNewPostPanel(chatroomid);
        }
    });
    tempNPPanel.getChildren()[9].addEvents({
        click:function(){
            enviaNewPostPanel(chatroomid);
        }
    });
}

function enviaNewPostPanel(chatroomid){
    var hasPic = $('checkBoxPic'+chatroomid).checked;
    if(chatroomid==0){
        if(hasPic){
            var request = new Request.File({

                url: '/chatsd/FileUploadServlet',

                onSuccess: function(response, res){
										  
                    //alert(response);
                    var texto = $('texto'+chatroomid).get('value');
                    var data = $('data1'+chatroomid).get('value') + " " + $('data2'+chatroomid).get('value');
                    doSend(getNewPostMessage(texto,hasPic,$('checkBoxAgora'+chatroomid).checked,response,data));
                    setNewPostPanel(chatroomid);
                }
            });
            $('formpicupload'+chatroomid).addEvent('submit', function(event){
                event.preventDefault();
                var file = $('inputPic'+chatroomid).files[0];
                request.append('file' , file);
                request.send();
            });
            //$('formpicupload'+chatroomid).submit();
            $('butSubmit'+chatroomid).click();
        } else {
            var texto = $('texto'+chatroomid).get('value');
            var data = $('data1'+chatroomid).get('value') + " " + $('data2'+chatroomid).get('value');
            doSend(getNewPostMessage(texto,hasPic,$('checkBoxAgora'+chatroomid).checked,"",data));
            setNewPostPanel(chatroomid);
        }
    }else {
        
}
}

function setEditPostPanel(chatroomid, postid){
    var chatElement = $(chats[chatroomid]);
    chatElement.getChildren()[1].empty();
    
    var tempEPPanel = editPostPanel.clone();
    chatElement.getChildren()[1].adopt(tempEPPanel);
    tempEPPanel.set('id', 'editPostDiv'+chatroomid);
    
    tempEPPanel.getChildren()[2].set('id', 'edittexto'+chatroomid);
    tempEPPanel.getChildren()[3].set('id', 'editbut1'+chatroomid);
    tempEPPanel.getChildren()[4].set('id', 'editbut2'+chatroomid);
    
    tempEPPanel.getChildren()[4].addEvents({
        click:function(){
            setNewPostPanel(chatroomid);
        }
    });
    
    if(chatroomid==0){
        tempEPPanel.getChildren()[3].addEvents({
            click:function(){
                doSend(getEditPostMessage($('edittexto'+chatroomid).get('value'), knownDB.posts[postid].id));
                setNewPostPanel(chatroomid);
            }
        });
        tempEPPanel.getChildren()[2].set('value', knownDB.posts[postid].text);
    }else {
        
}
}

function setCommentPostPanel(chatroomid, postid){
    var chatElement = $(chats[chatroomid]);
    chatElement.getChildren()[1].empty();
    
    
    var tempEPPanel = newCommentPanel.clone();
    chatElement.getChildren()[1].adopt(tempEPPanel);
    tempEPPanel.set('id', 'commentPostDiv'+chatroomid);
    
    tempEPPanel.getChildren()[2].set('id', 'commenttexto'+chatroomid);
    tempEPPanel.getChildren()[3].set('id', 'commentbut1'+chatroomid);
    tempEPPanel.getChildren()[4].set('id', 'commentbut2'+chatroomid);
    
    tempEPPanel.getChildren()[4].addEvents({
        click:function(){
            setNewPostPanel(chatroomid);
        }
    });
    if(chatroomid==0){
        tempEPPanel.getChildren()[3].addEvents({
            click:function(){
                doSend(getNewCommentMessage($('commenttexto'+chatroomid).get('value'), knownDB.posts[postid].id));
                setNewPostPanel(chatroomid);
            }
        });
    }
}

function getUserNameById(id){
    for(var t=0; t<knownUsers.length; t++){
        if(knownUsers[t].password==id){
            return knownUsers[t].username;
        }
    }
    return "unknown";
}

function getUserIdByName(name){
    for(var t=0; t<knownUsers.length; t++){
        if(knownUsers[t].username==name){
            return knownUsers[t].password;
        }
    }
    return -1;
}


function setNewMPPanel(respname, prevMessage){
    $('pmPanelDiv').getChildren()[4].empty();
    var tempNewMpPanel = newMPPanel.clone();
    tempNewMpPanel.set('id', 'newMpPanel');
    var rows = tempNewMpPanel.getChildren()[0].getChildren()[0].getChildren();
    rows[0].getChildren()[1].set('text', loggedUser.username);
    rows[1].getChildren()[1].set('id', 'newmptos');
    rows[1].getChildren()[2].getChildren()[0].set('id', 'selectDestUser');
    var optionsForSelect = "";
    for (var y=0; y<knownUsers.length; y++){
        optionsForSelect += '<option value="'+knownUsers[y].password+'">'+knownUsers[y].username+'</option>';
    }
    rows[1].getChildren()[2].getChildren()[0].set('html', optionsForSelect);
    rows[1].getChildren()[2].getChildren()[1].addEvents({
        click: function (){
            var names=[],ids=[];
            ids = $('hiddenTos').get('value').split(',');
            if(ids[0]==''){
                ids = [];
            }
            if(ids.indexOf($('selectDestUser').get('value'))==-1){
                ids.push($('selectDestUser').get('value'));
                for(var f=0; f<ids.length; f++){
                    names.push(getUserNameById(ids[f]));
                }
                $('newmptos').set('text', names.join());
                $('hiddenTos').set('value', ids.join());
            }
        }
    });
    rows[1].getChildren()[2].adopt(new Element('input', {
        type: 'hidden',
        id: 'hiddenTos',
        name : 'tos[]',
        value : ""
    }));
    
    rows[2].getChildren()[1].getChildren()[0].set('id', 'newmptextarea');

    rows[2].getChildren()[2].getChildren()[0].set('id', 'creatempbut');
    
    rows[2].getChildren()[2].getChildren()[0].addEvents({
            click :  function () {
                var ids=[];
                ids = $('hiddenTos').get('value').split(',');
                if(ids.length>0){
                    doSend(getNewPmMessage($('newmptextarea').get('value'), ids));
                }
            }
        });
    
    $('pmPanelDiv').getChildren()[4].adopt(tempNewMpPanel);

    //Configura resposta
    if(respname!=''){
        var names=[],ids=[];
        var respId = getUserIdByName(respname);
        if(respId>=0){
            
            ids.push(respId)
            names.push(respname);
            
            $('newmptos').set('text', names.join());
            $('hiddenTos').set('value', ids.join());
        }
        $('newmptextarea').set('text', '\n\n---------------------------\nMessage from: '+respname+'\n---------------------------\n'+prevMessage);
    }
    
    
    
}


function setViewMPPanel(postInfo){
    $('pmPanelDiv').getChildren()[4].empty();
    var tempNewMpPanel = newMPPanel.clone();
    tempNewMpPanel.set('id', 'newMpPanel');
    var rows = tempNewMpPanel.getChildren()[0].getChildren()[0].getChildren();
    rows[0].getChildren()[1].set('text', postInfo.from);
    rows[1].getChildren()[1].set('id', 'newmptos');
    rows[1].getChildren()[2].setStyle('display', 'none');
    
    //rows[1].getChildren()[2].getChildren()[1].set('display', 'none');
    
    
    rows[2].getChildren()[1].getChildren()[0].set('id', 'newmptextarea');
    rows[2].getChildren()[1].getChildren()[0].set('value', postInfo.text);
    rows[2].getChildren()[2].setStyle('display', 'none');
    $('pmPanelDiv').getChildren()[4].adopt(tempNewMpPanel);

    
    
}

function reloadPMs(){
    control.selectedPM = -1;
    $('listaMP').empty();
    
    for(var p=0; p<knownDB.pms.length; p++){
        var tempPm = mpItemPanel.clone();
        tempPm.set('id', 'pm'+p);
        tempPm.getChildren()[0].getChildren()[0].getChildren()[0].getChildren()[0].set('text', knownDB.pms[p].from);
        tempPm.getChildren()[0].getChildren()[0].getChildren()[0].getChildren()[1].set('text', knownDB.pms[p].text.substring(0,20));
        tempPm.getChildren()[0].getChildren()[0].getChildren()[0].getChildren()[2].set('text', knownDB.pms[p].data);
        tempPm.set('pmid', p+'');
        tempPm.addEvents({
            click :  function () {
                if(control.selectedPM==parseInt(this.get('pmid'))){
                    this.setStyle('background-color', 'white');
                    control.selectedPM = -1;
                    setNewMPPanel("", "");
                }else {
                    if(control.selectedPM>=0){
                        $('pm'+control.selectedPM).setStyle('background-color', 'white');
                    }
                    setViewMPPanel(knownDB.pms[this.get('pmid')]);
                    this.setStyle('background-color', 'silver');
                    control.selectedPM = parseInt(this.get('pmid'));
                }
            }
        });
        $('listaMP').adopt(tempPm);
    }
}



function parseMessageWeb(message){
    //alert(message);
    var c1 = message[0];
    var c2 = message[1];
    var dataString = message.substr(2,message.length-2);
    var dataObj = JSON.decode(dataString);
    if(c1=='1'){
        if(c2=='1'){
            setDisconnected();
        }else if(c2=='2'){
            setConnectionAccepted(dataObj[0]);
        }else if(c2=='3'){
            setAuthFailMessage(dataObj[0]);
        }else if(c2=='4'){
            setAuthenticated(dataObj[0]);
        }else if(c2=='5'){
            setEsteUser(dataObj);
        }
    }else if(c1=='2'){
        if(c2=='1'){
            
        }else if(c2=='2'){
            updatePosts(dataObj);
            updateChatRoomPosts(0);
        }else if(c2=='3'){
            updateUsers(dataObj);
            updateChatRoomUsers(0);
        }
    }else if(c1=='3'){
        if(c2=='1'){
            updatePMs(dataObj);
        }else if(c2=='2'){
        }else if(c2=='3'){
    }
    }else if(c1=='4'){
        if(c2=='1'){
            updateChannelsDB(dataObj);
        }else if(c2=='2'){
            if($('room_'+dataObj.name)!=null){
                $(dataObj.name+'msgs').adopt(new Element('p',{
                    'text':dataObj.data
                }))
            }
        }
    }
}





var chats = [];



function displayMsg(msg) {
    writeToHistory(msg);
}

function setDisconnected() {
    writeToHistory("disconnected");
    $('mainContent').empty();
    $('mainButtons').empty();
}

function setConnectionAccepted(conid) {
    writeToHistory("connected");
    $('mainButtons').adopt(mainButton('loginBut', 'Login', function(){
        setLoginPanel();
    }));
    setLoginPanel();
}

function setAuthFailMessage(msg) {
    writeToHistory(msg);
}

function setAuthenticated(username) {
    writeToHistory("authenticated "+username);
    $('mainContent').empty();
    $('mainButtons').empty();
    $('mainButtons').adopt(mainButton('chatBut', 'Sala Principal', function(){
        clickedMBut('mainChatRoom');
    }));
    $('mainButtons').adopt(mainButton('mpBut', 'Mensagens', function(){
        clickedMBut('pmPanelDiv');
        setNewMPPanel("", "");
    }));
    initializeApplicationPanels();
    createChannelsListPanel();
}

function updatePosts(db) {
    knownDB.posts = [];
    knownDB.comments = [];
    for(var j=0; j<db.length; j++){
        if(!db[j].comment){
            knownDB.posts.push(db[j]);
        }else{
            knownDB.comments.push(db[j]);
        }
    }
}

function updateUsers(udb) {
    knownDB.users = [];
    for(var j=0; j<udb.length; j++){
        knownDB.users.push(udb[j]);
        adduser(udb[j]);
    }
}

function updatePMs(db) {
    knownDB.pms = [];
    for(var j=0; j<db.length; j++){
        knownDB.pms.push(db[j]);
    }
    reloadPMs();
}

function setEsteUser(esteUser) {
    loggedUser.username = esteUser.username;
    loggedUser.id = parseInt(esteUser.password);
    writeToHistory("received esteUser: "+esteUser.username);
}


